package com.thz.system.service.gif.impl;

import com.thz.common.dto.gif.ConversionVideoToGifResponseDTO;
import com.thz.system.service.gif.IConversionCacheService;
import com.thz.system.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.thz.common.constants.RedisConstants.CACHE_KEY_PREFIX;


/**
 * 转换任务缓存服务实现
 * 使用Redis缓存转换任务状态，减少数据库查询
 * 
 * @author THZ
 * @date 2025
 */
@Slf4j
@Service
public class ConversionCacheServiceImpl implements IConversionCacheService {
    
    @Autowired
    private RedisUtils redisUtils;

    
    @Override
    public void cacheConversionStatus(Long taskId, ConversionVideoToGifResponseDTO response, long ttlSeconds) {
        try {
            String key = CACHE_KEY_PREFIX + taskId;
            log.info("🔄 开始缓存转换任务: taskId={}, key={}, ttl={}秒", taskId, key, ttlSeconds);
            
            redisUtils.setObject(key, response, ttlSeconds, TimeUnit.SECONDS);
            
            log.info("✅ 缓存转换任务状态成功: taskId={}, key={}, ttl={}秒", taskId, key, ttlSeconds);
        } catch (Exception e) {
            log.error("❌ 缓存转换任务状态失败: taskId={}, error={}", taskId, e.getMessage(), e);
            // 不抛出异常，避免影响主流程，但会在日志中明确显示错误
        }
    }
    
    @Override
    public ConversionVideoToGifResponseDTO getCachedConversionStatus(Long taskId) {
        String key = CACHE_KEY_PREFIX + taskId;
        ConversionVideoToGifResponseDTO response = redisUtils.getObject(key, ConversionVideoToGifResponseDTO.class);
        
        if (response != null) {
            log.info("缓存命中 - taskId={}, key={}", taskId, key);
        } else {
            log.info("缓存未命中 - taskId={}, key={}", taskId, key);
        }
        
        return response;
    }
    
    @Override
    public void removeCachedConversionStatus(Long taskId) {
        String key = CACHE_KEY_PREFIX + taskId;
        redisUtils.delete(key);
        log.info("删除缓存的转换任务状态: taskId={}, key={}", taskId, key);
    }
    
    @Override
    public void updateConversionStatus(Long taskId, ConversionVideoToGifResponseDTO response) {
        String key = CACHE_KEY_PREFIX + taskId;
        
        // 获取剩余TTL
        Long ttl = redisUtils.getExpire(key, TimeUnit.SECONDS);
        
        if (ttl != null && ttl > 0) {
            // 保持原有的TTL
            redisUtils.setObject(key, response, ttl, TimeUnit.SECONDS);
            log.info("更新缓存的转换任务状态: taskId={}, key={}, 保持TTL={}秒", taskId, key, ttl);
        } else {
            // 默认缓存10分钟
            redisUtils.setObject(key, response, 600, TimeUnit.SECONDS);
            log.info("更新缓存的转换任务状态: taskId={}, key={}, 新TTL=600秒", taskId, key);
        }
    }
}

